package cn.wsxiot.servlet;

import cn.wsxiot.dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 构造函数->init()->destroy()
 * 下列情形servlet被装载
 * 1.第一次请求
 * 2.<load-on-startup>1</load-on-startup>
 * 3.servlet被修改后
 */
@WebServlet(name = "LoginServlet")
public class LoginServlet extends HttpServlet {

    private UserDao userDao = null;

    public LoginServlet(){
        System.out.println("构造servlet");
    }

    public void init() throws ServletException {
        userDao = new UserDao();
        System.out.println("初始化servlet");
    }

    public void destroy() {
        System.out.println("销毁servlet");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uemail = request.getParameter("uemail");
        String upasswd = request.getParameter("upasswd");
        if(userDao.login(uemail, upasswd)){
            System.out.println("登陆成功");
            request.getSession().setAttribute("uemail", uemail);
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }else{
            System.out.println("登陆失败");
            response.sendRedirect(request.getContextPath() + "/login.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
